package com.java.jvm.heap;
import java.lang.ref.*;
class RefObject{
    @Override
    protected void finalize() throws Throwable {
        System.out.println("==finalize()==");
    }
}
//-Xmx5m -Xms5m
public class ReferenceTests {
    static void createObjs(){
        byte[] data1=new byte[1024*1024];
        byte[] data2=new byte[1024*1024];
        byte[] data3=new byte[1024*1024];
        byte[] data4=new byte[1024*1024];
    }
    static void strongReference(){
        RefObject o1=new RefObject();//o1为强引用
        //手动GC
        System.gc();
        createObjs();
    }
    //软引用(此引用引用的对象会在内存不足时被回收)
    public static void softReference(){
        RefObject obj = new RefObject();
        SoftReference<RefObject> soft = new SoftReference<>(obj);
        obj = null;
        //get方法用于获取软引用引用的对象
        System.out.println(soft.get());
         //手动gc
        //System.gc();
        //创建对象，让内存不足时触发gc
        createObjs();
        System.out.println(soft.get());
    }
    //弱引用(此引用引用的对象可能会在触发gc时被回收)
    public static void weakReference(){
        RefObject obj = new RefObject();
        WeakReference<RefObject> soft = new WeakReference<>(obj);
        obj = null;
        System.out.println(soft.get());
        //手动gc
        System.gc();
        //创建对象，让内存不足时触发gc
        //createObjs();
        System.out.println(soft.get());
    }

    //PhantomReference 为虚引用，此引用引用对象，生命力极弱，相当于没有引用
    //使用此引用主要用于监控对象是否被回收了
    public static void phantomReference(){
        ReferenceQueue<Object> rq = new ReferenceQueue<>();
        Object obj = new Object();
        PhantomReference<Object> phantomReference =
                new PhantomReference<>(obj,rq);
        obj = null;
        System.out.println(phantomReference.get());//null
        System.gc();
        Reference<Object> r = (Reference<Object>)rq.poll();
        System.out.println(r);
    }

    public static void main(String[] args) {
            strongReference();
        //  softReference();
       //   weakReference();

        phantomReference();
    }
}
